#include "rk_defines.h"
#include "rk_debug.h"
#include "rknn_api.h"

#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <string>
#include <vector>
#include <cmath>

#include "taiic_avsr.h"
#include "taiic_rknn.h"
#include <dirent.h> 
#include <iostream> 
#include <fstream>
using namespace std;

void EnumerateFilesInDirectory(const std::string& path, std::vector<std::string>& files) {  
    DIR* dir;  
    struct dirent* ent;  
    if ((dir = opendir(path.c_str())) != NULL) {  
        while ((ent = readdir(dir)) != NULL) {  
            // 忽略目录和非文件条目  
            if (ent->d_type == DT_REG) {  
                files.push_back(ent->d_name);  
            }  
        }  
        closedir(dir);  
    } else {  
        // 无法打开目录  
        perror("");  
        return;  
    }  
}

/*
rknntoolkit_1.5.0  output_type is int8, need use zp and  scale to trans float
*/

static inline int64_t getCurrentTimeUs()
{
  struct timeval tv;
  gettimeofday(&tv, NULL);
  return tv.tv_sec * 1000000 + tv.tv_usec;
}



int main(int argc, char *argv[])
{
  string file_str1,file_str2;
  AVSR_TOOLKIT_MODEL_CTX_S *avsr_ctx; // 模型推理相关

  // char*                    input1_path        = argv[1]; //video
  // char*                    input2_path        = argv[2]; //audio
  const char* input1_path = NULL; //video
  const char* input2_path = NULL; //audio
  string audio_path;
  string video_path;
  ofstream outfile("result.txt",std::ios::app);//追加  
  //检查文件是否成功打开  
  if (!outfile.is_open()) 
  {  
    std::cerr << "Unable to open file result.txt";  
    return 1; // 返回非零值表示错误  
  } 

  int i=0;

  FILE* fp=NULL;
  FILE* fp1=NULL;
  //20240611 add by mtd/////////////////////////////
  string path1 = "video/";
  string path2 = "audio/";   
  vector<string> files;  
  EnumerateFilesInDirectory(path1, files); 
  cout << "Number of files in the directory: " << files.size() << std::endl;  
  for (const auto& file : files) 
  {  
      cout << "File: " << file << std::endl;  
      video_path = path1+file;
      audio_path = path2+file;
      printf("%s,%s\n",video_path.c_str(),audio_path.c_str());
      input1_path = video_path.c_str();
      input2_path = audio_path.c_str();
      /*--------------------------------------------------------------------*/
      //模型推理相关
      avsr_ctx = reinterpret_cast<AVSR_TOOLKIT_MODEL_CTX_S *>(malloc(sizeof(AVSR_TOOLKIT_MODEL_CTX_S))); // 分配内存空间
      memset(avsr_ctx, 0, sizeof(AVSR_TOOLKIT_MODEL_CTX_S));

      avsr_ctx->modelPath = AVSR_MODEL_PATH; 

      avsr_rknn_toolkit_config_init(avsr_ctx);
      avsr_rknn_toolkit_io_init(avsr_ctx);

      //Get Input Data From CPU
      unsigned char* input_data[avsr_ctx->io_num.n_input];
      i = 0;
      input_data[i] = new unsigned char[avsr_ctx->input_attrs[i].size]; //设置输入大小
      fp = fopen( input1_path,"rb");
      RK_LOGI("==load fiel 1 is %s==\n",input1_path);
      if (fp == NULL)
      {
        perror("open failed!");
        return -1;
      }
      fread(input_data[i], avsr_ctx->input_attrs[i].size, 1, fp);
      fclose(fp);
      if (!input_data[i]) {
        return -1;
      }

      i =1;
      input_data[i] = new unsigned char[avsr_ctx->input_attrs[i].size]; //设置输入大小
      fp1 = fopen(input2_path, "rb");
      RK_LOGI("==load fiel 2 is %s==\n",input2_path);
      if(fp1 == NULL)
      {
        perror("open failed!");
        return -1;
      }
      fread(input_data[i], avsr_ctx->input_attrs[i].size,1,fp1);
      fclose(fp1);
      if (!input_data[i]) 
      {
        return -1;
      }

      avsr_rknn_toolkit_data_refresh(avsr_ctx,  input_data);
    

      int64_t start_us = getCurrentTimeUs();
      // Set input
      int ret = rknn_run(avsr_ctx->context, NULL);
      if(ret < 0)
      {
        RK_LOGE("===rknn_run_fail! ret = %d\n", ret);
        return -1;
      }
      int64_t elapse_us = getCurrentTimeUs() - start_us;
      RK_LOGD(" Elapse Time = %.2fms, FPS = %.2f\n", elapse_us / 1000.f, 1000.f * 1000.f / elapse_us);

      MODEL_RESULT_S rknn_result = avsr_rknn_toolkit_result_int8(avsr_ctx);

      printf("===result label is %d, prob is %f====\n", rknn_result.label, rknn_result.prob);
      //写入字符串  
      outfile <<file<<": result label:" <<rknn_result.label<<",prob: "<<rknn_result.prob<< std::endl;
      
      //遍历完将.dat删除
      file_str1="rm -rf /data/" + path1 + file;
      file_str2="rm -rf /data/" + path2 + file;
      // printf("%s,%s\n",file_str1.c_str(),file_str2.c_str());
      system(file_str1.c_str());
      system(file_str2.c_str());
      
      // destroy
      rknn_destroy(avsr_ctx->context);

      for (int i = 0; i < avsr_ctx->io_num.n_input; i++) 
      {
         free(input_data[i]);
      }
      /*--------------------------------------------------------------------*/
  }
   // 关闭文件  
   outfile.close();     
   return 0;
}